package com.qingzhuge.web.filter;

import com.qingzhuge.common.utils.DateUtil;
import com.qingzhuge.common.utils.IpUtils;
import com.qingzhuge.common.utils.WebUtil;
import com.qingzhuge.autoconfigure.QingTingProperties;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

/**
 * @author : zero.xiao
 * @description : 跨站请求
 * @modified :
 */
@Slf4j
@Component
public class CsrfFilter implements Filter {
    private final QingTingProperties qingTingProperties;
    /**
     * 白名单
     */
    private List<String> whiteUrls;

    private int size = 0;

    public CsrfFilter(QingTingProperties qingTingProperties) {
        this.qingTingProperties = qingTingProperties;
    }

    @Override
    public void init(FilterConfig filterConfig) {
        whiteUrls = qingTingProperties.getFilter().getCsrfWhiteUrls();
        size = null == whiteUrls ? 0 : whiteUrls.size();
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) {
        try {
            HttpServletRequest req = (HttpServletRequest) request;
            HttpServletResponse res = (HttpServletResponse) response;
            // 获取请求url地址
            String url = req.getRequestURL().toString();
            String referurl = req.getHeader("Referer");
            if (WebUtil.isWhiteRequest(referurl, size, whiteUrls)) {
                chain.doFilter(request, response);
            } else {
                req.getRequestDispatcher("/").forward(req, res);
                // 记录跨站请求日志
                String date = DateUtil.getDate();
                String clientIp = IpUtils.getIpAddr(req);
                log.warn("跨站请求---->>>{}||{}||{}||{}", clientIp, date, referurl, url);
                WebUtil.writer(response,"{\"code\":\"308\",\"message\":\"错误的请求头信息\"}");
            }

        } catch (Exception e) {
            log.error("doFilter", e);
        }
    }

    @Override
    public void destroy() {
    }
}
